package com.fs.dao.Impl;

import com.fs.dao.QuestionsDao;
import com.fs.pojo.Questions;
import com.fs.utils.JDBCUtils;
import com.fs.utils.MyConnectionPool;
import com.fs.vo.QuestionVO;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

public class QuestionsDaoImpl implements QuestionsDao {

    @Override
    public List<Questions> queryAllQuestionsByPaperId(String paperId) {

        String sql = "select * from tb_questions where paper_id = ?";

        return JDBCUtils.executeQurey(sql,Questions.class,paperId);
    }



    @Override
    public int deleteAllByPaperId(String paperID) {
        String sql = "delete from tb_questions where paper_id = ?";
        return JDBCUtils.executeUpdate(sql,paperID);
    }

    @Override
    public int insertList(List<Questions> questions) {

        try {
            Connection connection = MyConnectionPool.getConnection();

            String[] fields ={"id", "paperId", "stem", "options", "result", "type", "score", "analysis"};
            String sql = "insert into tb_questions (id, paper_id, stem, options, result, type, score, analysis) values ";

            Class<Questions> aclass = Questions.class;

            for(int i = 0 ; i < questions.size() ; i++)
                if(i == questions.size()-1)
                    sql+="(?,?,?,?,?,?,?,?)";
                else
                    sql+="(?,?,?,?,?,?,?,?),";


            PreparedStatement prep = connection.prepareStatement(sql);

            for(int i = 0 ; i < questions.size() ; i++)
                  for(int j = 0; j < fields.length ; j++){
                      Field field = aclass.getDeclaredField(fields[j]);
                      field.setAccessible(true);
                      prep.setObject(i*fields.length + j +1,field.get(questions.get(i)));
                  }

            int i = prep.executeUpdate();

            prep.close();
            connection.close();

            return i;

        } catch (Exception e) {
            e.printStackTrace();
        }



        return 0;
    }

    @Override
    public Questions queryById(String id) {
        return null;
    }

    @Override
    public List<Questions> queryAll() {
        return null;
    }

    @Override
    public int insert(Questions obj) {
        String sql = "insert into tb_questions(id, paper_id, stem, options, result, type, score, analysis) values (?,?,?,?,?,?,?,?)";
        return JDBCUtils.executeUpdate(sql,obj);
    }

    @Override
    public int deleteById(String id) {
        return 0;
    }

    @Override
    public int update(Questions obj) {
        return 0;
    }
}
